//
//  RealTimeHBReportController.m
//  CoolTennisBall
//
//  Created by Coollang on 16/8/3.
//  Copyright © 2016年 CoolLang. All rights reserved.
//

#import "RealTimeHBReportController.h"
#import "RealTimeTrainModel.h"
#import "PNChart.h"
#import "MTScatterChart.h"
#import "ChartItem.h"
#import "NSDate+FormateString.h"
#import "RealTimeHBFrontController.h"
#import "RealTimeHBBackController.h"


//#define textLargetFont  SanFranciscoFont(26)
#define textSmallFont [UIFont systemFontOfSize:11]

#define totalStringTextFont SanFranciscoFont(23)
#define totalStringtextColor [UIColor colorWithHex:0x7c7b81 alpha:1.0]

@interface RealTimeHBReportController () <UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *trainTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *trainStrengthLabel;

@property (weak, nonatomic) IBOutlet UILabel *completeLlabel;

@property (weak, nonatomic) IBOutlet UIScrollView *scorllView;



@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentControl;

@property (nonatomic, strong) NSMutableArray *foreHandDotItems;
@property (nonatomic, strong) NSMutableArray *backHanddotItems;


@property (nonatomic, copy)NSString *trainStrengthString; // 训练强度
@property (nonatomic, copy)NSString *completeSituation; //完成(度)情况

@property (nonatomic, assign)NSInteger foreHandHitBallNumber;//正手总击球数
@property (nonatomic, assign)NSInteger foreHandStandardNumber;//正手达标数
@property (nonatomic, assign)CGFloat foreHandPassRate;//正手通过率
@property (nonatomic, copy)NSString *foreHandaverageSpeed; //正手平均速率;

@property (nonatomic, assign)NSInteger backHandHitBallNumber;//反手总击球数
@property (nonatomic, assign)NSInteger backHandStandardNumber;//反手达标数
@property (nonatomic, assign)CGFloat backHandPassRate;//反手通过率
@property (nonatomic, copy)NSString *backHandaverageSpeed; //反手平均速率;


@property (nonatomic, strong) RealTimeHBFrontController *forehandVc;
@property (nonatomic, strong) RealTimeHBBackController *backhandVc;

@end

@implementation RealTimeHBReportController {
    
     NSInteger foreHandShangXuanNum;
     NSInteger foreHandPingJiNum;
     NSInteger foreHandXueQiuNum ;
     NSInteger foreHandShangXuanGoodNum ;
     NSInteger foreHandPingJiGoodNum ;
     NSInteger foreHandXueQiuGoodNum ;
    
     NSInteger backHandShangXuanNum;
     NSInteger backHandPingJiNum;
     NSInteger backHandXueQiuNum;
     NSInteger backHandShangXuanGoodNum ;
     NSInteger backHandPingJiGoodNum;
     NSInteger backHandXueQiuGoodNum;
     UIFont *textLargetFont;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.scorllView.delegate = self;
    
    if ([NSBundle currentLanguageIsChinese]) {
        textLargetFont = SanFranciscoFont(26);
    }else {
        textLargetFont = SanFranciscoFont(23);
    }
    
    [self defalutvalue];
    [self disPoseTrainData];
    [self setUpUi];
    [self configerForeHandData];
    [self configerBackHandData];
}

- (IBAction)segmentValueChange:(UISegmentedControl *)sender {
    
    self.scorllView.contentOffset = CGPointMake(sender.selectedSegmentIndex * self.scorllView.frame.size.width, 0);

}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    self.segmentControl.selectedSegmentIndex = scrollView.contentOffset.x / scrollView.bounds.size.width;
    
    if (self.segmentControl.selectedSegmentIndex == 0) {
        [self configerForeHandData];
    }else {
        [self configerBackHandData];
    }
    
}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"RealTimeHBForeHandReport"]) {
        self.forehandVc = segue.destinationViewController;
        self.forehandVc.frontTargetSpeed = [self.trainModel.frontHandPaiSuTargetSpeed floatValue];
    }else if ([segue.identifier isEqualToString:@"RealTimeHBBackHandReport"]){
        self.backhandVc = segue.destinationViewController;
        self.backhandVc.backTargetSpeed = [self.trainModel.backHandPaiSuTargetSpeed floatValue];
    }
}

- (void)configerForeHandData {
   
    
    NSString *paiUnitString = NSLocalizedString(@"Unit.Shots", nil);

    // 总击球数
    NSString *totalString = [NSString stringWithFormat:@"%zd%@",_foreHandHitBallNumber, paiUnitString];
    
    NSAttributedString *totalAttr = [NSAttributedString attributedString:totalString subString:@[@(_foreHandHitBallNumber).stringValue, paiUnitString] colors:@[totalStringtextColor, totalStringtextColor] fonts:@[totalStringTextFont, textSmallFont]];
    // 达标拍数
    NSString *stantardString = [NSString stringWithFormat:@"%zd%@",_foreHandStandardNumber, paiUnitString];
    
    NSAttributedString *standardAttr = [NSAttributedString attributedString:stantardString subString:@[@(_foreHandStandardNumber).stringValue, paiUnitString] colors:@[totalStringtextColor, totalStringtextColor] fonts:@[totalStringTextFont, textSmallFont]];
    
    // 通过率
    NSString *passRateString = [NSString stringWithFormat:@"%0.f%%",_foreHandPassRate * 100];
    
    NSAttributedString *passRateAttr = [NSAttributedString attributedString:passRateString subString:@[passRateString] colors:@[totalStringtextColor] fonts:@[totalStringTextFont]];
    
    // 设置上旋、平击、削球
    NSString *shangxuanText = [NSString stringWithFormat:@"%zd/%zd", foreHandShangXuanGoodNum,foreHandShangXuanNum];
    NSString *pingjitext = [NSString stringWithFormat:@"%zd/%zd", foreHandPingJiGoodNum,foreHandPingJiNum];
    NSString *xueqiutext = [NSString stringWithFormat:@"%zd/%zd", foreHandXueQiuGoodNum,foreHandXueQiuNum];
    
    // 设置平均速度和散点视图
    NSString *avg = _foreHandaverageSpeed;
    
    NSArray *dotItems = self.foreHandDotItems;
    
    CGFloat targetSpeed = [self.trainModel.frontHandPaiSuTargetSpeed floatValue];
    
    [self.forehandVc configerForeHandHitBallNum:totalAttr StandardNum:standardAttr passRate:passRateAttr sPXTexts:@{@"ShangXuan":shangxuanText, @"PingJi":pingjitext,@"XueQiu":xueqiutext} averageSpeed:avg dotItems:dotItems targetSpeed:targetSpeed];

}

- (void)configerBackHandData {
    
    NSString *paiUnitString = NSLocalizedString(@"Unit.Shots", nil);
    
    // 总击球数
    NSString *totalString = [NSString stringWithFormat:@"%zd%@",_backHandHitBallNumber, paiUnitString];
     NSAttributedString *totalAttr = [NSAttributedString attributedString:totalString subString:@[@(_backHandHitBallNumber).stringValue,paiUnitString] colors:@[totalStringtextColor, totalStringtextColor] fonts:@[totalStringTextFont, textSmallFont]];
    // 达标拍数
    NSString *stantardString = [NSString stringWithFormat:@"%zd%@",_backHandStandardNumber, paiUnitString];
    
    NSAttributedString *standardAttr = [NSAttributedString attributedString:stantardString subString:@[@(_backHandStandardNumber).stringValue, paiUnitString] colors:@[totalStringtextColor, totalStringtextColor] fonts:@[totalStringTextFont, textSmallFont]];
    
    // 通过率
    NSString *passRateString = [NSString stringWithFormat:@"%0.f%%",_backHandPassRate * 100];
    
    NSAttributedString *passRateAttr = [NSAttributedString attributedString:passRateString subString:@[passRateString] colors:@[totalStringtextColor] fonts:@[totalStringTextFont]];
    
    // 设置上旋、平击、削球
     NSString *shangxuanText = [NSString stringWithFormat:@"%zd/%zd", backHandShangXuanGoodNum,backHandShangXuanNum];
    NSString *pingjitext = [NSString stringWithFormat:@"%zd/%zd", backHandPingJiGoodNum,backHandPingJiNum];
    NSString *xueqiutext = [NSString stringWithFormat:@"%zd/%zd", backHandXueQiuGoodNum,backHandXueQiuNum];
    
    // 设置平均速度和散点视图
    NSString *avg = _backHandaverageSpeed;
    
    NSArray *dotItems = self.backHanddotItems;

    CGFloat targetSpeed= [self.trainModel.backHandPaiSuTargetSpeed floatValue];
    [self.backhandVc configerBackHandHitBallNum:totalAttr StandardNum:standardAttr passRate:passRateAttr sPXTexts:@{@"ShangXuan":shangxuanText, @"PingJi":pingjitext,@"XueQiu":xueqiutext} averageSpeed:avg dotItems:dotItems targetSpeed:targetSpeed];
}


#pragma mark - 设置数据
- (void)setUpUi {
    NSString *minUnitString = NSLocalizedString(@"Unit.Minute", nil);
    
    NSString *timelongString = [NSString stringWithFormat:@"%@%@",[self.trainModel trainTimeLong], minUnitString];
    self.trainTimeLabel.attributedText = [NSAttributedString attributedString:timelongString subString:@[[self.trainModel trainTimeLong],minUnitString] colors:@[kOrangeColor,kOrangeColor] fonts:@[textLargetFont, textSmallFont]];
    
    self.trainStrengthLabel.attributedText = [NSAttributedString attributedString:(_trainStrengthString) subString:@[_trainStrengthString] colors:@[kOrangeColor] fonts:@[textLargetFont]];
    self.completeLlabel.attributedText = [NSAttributedString attributedString:([self calculateCopleteSituation]) subString:@[[self calculateCopleteSituation]] colors:@[kOrangeColor] fonts:@[textLargetFont]];
}

#pragma mark - 数据处理
// 设置默认值
- (void)defalutvalue {
    foreHandShangXuanNum = 0;
    foreHandShangXuanGoodNum = 0;
    foreHandPingJiNum = 0;
    foreHandPingJiGoodNum = 0;
    foreHandXueQiuNum = 0;
    foreHandPingJiGoodNum = 0;
    
    backHandShangXuanNum = 0;
    backHandShangXuanGoodNum = 0;
    backHandPingJiNum = 0;
    backHandPingJiGoodNum = 0;
    backHandXueQiuNum = 0;
    backHandXueQiuGoodNum = 0;

}


- (void)disPoseTrainData {
    
    __weak typeof(self) weakSelf = self;
    [self.trainModel.chartItemArray enumerateObjectsUsingBlock:^(ChartItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [weakSelf analyzeForeHandBall:obj];
        [weakSelf analyzeBackHandBall:obj];
    }];
    
//    2.计算平均速度
    if (self.foreHandDotItems.count > 0) {
        __block CGFloat totalSpeed = 0;
        
        [self.foreHandDotItems enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            totalSpeed += obj.floatValue;
        }];
        _foreHandaverageSpeed = [NSString stringWithFormat:@"%0.f", totalSpeed /self.foreHandDotItems.count];
    }else {
        _foreHandaverageSpeed = @"0";
    }
    
    if (self.backHanddotItems.count > 0) {
        __block CGFloat totalSpeed = 0;
        
        [self.backHanddotItems enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            totalSpeed += obj.floatValue;
        }];
        _backHandaverageSpeed = [NSString stringWithFormat:@"%0.f", totalSpeed /self.backHanddotItems.count];
    }else {
        _backHandaverageSpeed = @"0";
    }
//  3.计算通过率
    if (_foreHandHitBallNumber > 0) {
        _foreHandPassRate = (_foreHandStandardNumber * 1.0) / _foreHandHitBallNumber;
    }else {
        _foreHandPassRate = 0;
    }
    if (_backHandHitBallNumber > 0) {
        _backHandPassRate = (_backHandStandardNumber * 1.0) / _backHandHitBallNumber;
    }else {
        _backHandPassRate = 0;
    }
//   4.计算训练强度
    
    NSTimeInterval spacing = [[NSDate dateWithUnixTimeStamp:self.trainModel.endRealTimeStamp] timeIntervalSinceDate:[self.trainModel date]];
    NSInteger rate = (NSInteger)roundf(60 * (_foreHandHitBallNumber + _backHandHitBallNumber) / (spacing + 1));
    
    switch ((rate / 8)) {
        case 0:
            _trainStrengthString = NSLocalizedString(@"Intensity.Low", nil);
            break;
        case 1:
            _trainStrengthString = NSLocalizedString(@"Intensity.Medium", nil);;
            break;
        default:
            _trainStrengthString = NSLocalizedString(@"Intensity.High", nil);;
            break;
    }
//    5.计算完成度
    self.completeSituation = [self calculateCopleteSituation];
    
}
// 分析正手球
- (void)analyzeForeHandBall:(ChartItem *)chartItem {
    
    if (chartItem.handDirectionType != HandDirectionTypeForeward) {
        return;
    }
    
    CGFloat maxSpeed = [chartItem.maxSpeed floatValue];
    CGFloat forehandTargetSpeed = [self.trainModel.frontHandPaiSuTargetSpeed floatValue]; // 正手目标拍速
    
    switch (chartItem.poseType) {
        case SportPoseTypeXuanQiu:{// 上旋
            foreHandShangXuanNum++;
            _foreHandHitBallNumber++;
            [self.foreHandDotItems addObject:@(maxSpeed)];
            if (maxSpeed >= forehandTargetSpeed) {
                foreHandShangXuanGoodNum++;
                 _foreHandStandardNumber++;
            }
        }
            break;
        case SportPoseTypePingJi:{ // 平击
            foreHandPingJiNum++;
            _foreHandHitBallNumber++;
            [self.foreHandDotItems addObject:@(maxSpeed)];
            if (maxSpeed >= forehandTargetSpeed) {
                foreHandPingJiGoodNum++;
                 _foreHandStandardNumber++;
            }
        }
            break;
        case SportPoseTypeXueQiu:{ // 削球
            foreHandXueQiuNum++;
            _foreHandHitBallNumber++;
            [self.foreHandDotItems addObject:@(maxSpeed)];
            if (maxSpeed >= forehandTargetSpeed) {
                foreHandXueQiuGoodNum++;
                 _foreHandStandardNumber++;
            }
        }
            break;
            
        default:
            break;
    }
    
}
// 分析反手球
- (void)analyzeBackHandBall:(ChartItem *)chartItem {
    
    if (chartItem.handDirectionType != HandDirectionTypeBackward) {
        return;
    }
    CGFloat maxSpeed = [chartItem.maxSpeed floatValue];
    CGFloat backhandTargetSpeed = [self.trainModel.backHandPaiSuTargetSpeed floatValue]; // 正手目标拍速
    
    switch (chartItem.poseType) {
        case SportPoseTypeXuanQiu: // 上旋
            backHandShangXuanNum++;
            _backHandHitBallNumber++;
            [self.backHanddotItems addObject:@(maxSpeed)];
            if (maxSpeed >= backhandTargetSpeed) {
                backHandShangXuanGoodNum++;
                _backHandStandardNumber++;
            }
            break;
        case SportPoseTypePingJi: // 平击
            backHandPingJiNum++;
            _backHandHitBallNumber++;
            [self.backHanddotItems addObject:@(maxSpeed)];
            if (maxSpeed >= backhandTargetSpeed) {
                backHandPingJiGoodNum++;
                _backHandStandardNumber++;
            }
            break;
        case SportPoseTypeXueQiu: // 削球
            backHandXueQiuNum++;
            _backHandHitBallNumber++;
            [self.backHanddotItems addObject:@(maxSpeed)];
            if (maxSpeed >= backhandTargetSpeed) {
                backHandXueQiuGoodNum++;
                _backHandStandardNumber++;
            }
            break;
            
        default:
            break;
    }
    
}
// 计算完成度
- (NSString *)calculateCopleteSituation {
    
    /*
     [ 0,0.6 ) ——较差 [ 0.6 , 0.8 )——及格 [ 0.8 , 0.9 )——良好 [ 0.9, 1 ]——优秀
     */
    
    CGFloat maxCase = 0.0f;
    
    if (self.trainModel.UploadTime == nil) {
        CGFloat case1 = foreHandShangXuanNum / [self.trainModel.frontHandShangXuanTarget floatValue];
        CGFloat case2 = foreHandPingJiNum / [self.trainModel.frontHandPingJiTarget floatValue];
        CGFloat case3 = foreHandXueQiuNum / [self.trainModel.frontHandXueQiuTarget floatValue];
        CGFloat case4 = backHandShangXuanNum / [self.trainModel.backHandShangXuanTarget floatValue];
        CGFloat case5 = backHandPingJiNum / [self.trainModel.backHandPingJiTarget floatValue];
        CGFloat case6 = backHandXueQiuNum / [self.trainModel.backHandXueQiuTarget floatValue];
        NSArray *caseArray = @[@(case1),@(case2),@(case3),@(case4),@(case5),@(case6)];
        
        NSNumber *complete = [caseArray sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:nil ascending:YES]]].lastObject;
        maxCase = complete.floatValue;
    }else {
        maxCase = self.trainModel.Frequency;
    }
    /**
     *  "Endurance.Perfect" = "优秀";
     "Endurance.Good" = "良好";
     "Endurance.Medium" = "中等";
     "Endurance.Weak" = "偏低";
     */
    if (maxCase >= 0 && maxCase < 0.6) {
        return NSLocalizedString(@"CompletionSattus.Poor", nil);
    }else if (maxCase >= 0.6 && maxCase < 0.8){
        return NSLocalizedString(@"CompletionSattus.General", nil);
    }else if (maxCase >= 0.8 && maxCase < 0.9){
        return NSLocalizedString(@"CompletionSattus.Good", nil);
    }else if (maxCase >= 0.9){
        return NSLocalizedString(@"CompletionSattus.Perfect", nil);
    }else {
        return @"";
    }
    
}

#pragma mark - 懒加载
- (NSMutableArray *)foreHandDotItems {
    if (_foreHandDotItems == nil) {
        _foreHandDotItems = [NSMutableArray array];
    }
    return _foreHandDotItems;
}
- (NSMutableArray *)backHanddotItems {
    if (_backHanddotItems == nil) {
        _backHanddotItems = [NSMutableArray array];
    }
    return _backHanddotItems;
}

@end



